package cn.waynexuan.tool;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

public class Month4WeekSegment {
	private int firstWeek=1;
	private int firstDayOfWeek=Calendar.SUNDAY;

	public List<List<Month4Week>> segmentYear(int year) {
		List<List<Month4Week>> monthList = new ArrayList<>(12);
		for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {
			monthList.add(segmentMonth(year, m));
		}
		return monthList;
	}

	public List<Month4Week> segmentMonth(int year, int month) {
		LinkedList<Month4Week> weeks = new LinkedList<>();
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.setFirstDayOfWeek(firstDayOfWeek);
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		//第一个七天
		calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
		//第一个完整周的第一天
		calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);

		int firstDayOfMonth = 1;
		int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		int firstDayOfIntactWeeks = calendar.get(Calendar.DAY_OF_MONTH);
		int lastDayOfIntactWeeks = 0;

		while (calendar.get(Calendar.MONTH) == month) {
			int startDay = calendar.get(Calendar.DAY_OF_MONTH);
			calendar.add(Calendar.DAY_OF_MONTH, 6);
			if (calendar.get(Calendar.MONTH) != month) {
				break;
			}
			lastDayOfIntactWeeks = calendar.get(Calendar.DAY_OF_MONTH);
			weeks.add(new Month4Week(year, month, startDay, lastDayOfIntactWeeks));
			calendar.add(Calendar.DAY_OF_MONTH, 1);
		}

		if (weeks.size() == 3) {
			int daysBeforeIntactWeek = firstDayOfIntactWeeks - firstDayOfMonth;
			int daysAfterIntactWeeks = lastDayOfMonth - lastDayOfIntactWeeks;
			if (daysBeforeIntactWeek >= daysAfterIntactWeeks) {
				weeks.getLast().setEndDay(lastDayOfMonth);
				weeks.addFirst(new Month4Week(year, month, firstDayOfMonth, firstDayOfIntactWeeks - 1));
			} else {
				weeks.getFirst().setStartDay(firstDayOfMonth);
				weeks.add(new Month4Week(year, month, lastDayOfIntactWeeks + 1, lastDayOfMonth));
			}
		} else {
			weeks.getFirst().setStartDay(firstDayOfMonth);
			weeks.getLast().setEndDay(lastDayOfMonth);
		}
		int week = firstWeek;
		for (Month4Week month4Week : weeks) {
			month4Week.setWeek(week++);
		}
		return new ArrayList<>(weeks);
	}

	public int getFirstWeek() {
		return firstWeek;
	}

	public void setFirstWeek(int firstWeek) {
		this.firstWeek = firstWeek;
	}

	public int getFirstDayOfWeek() {
		return firstDayOfWeek;
	}

	public void setFirstDayOfWeek(int firstDayOfWeek) {
		this.firstDayOfWeek = firstDayOfWeek;
	}
}
